package com.pingan.generator.api.util;

import java.io.IOException;
import java.text.SimpleDateFormat;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * json处理器
 * @author ouyangenkun051
 *
 */
public  class JsonUtil {
	private static ObjectMapper mapper = new ObjectMapper() 
			.setSerializationInclusion(Include.NON_NULL)
	        .enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
	        .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
	         .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
	        .enable(MapperFeature.USE_ANNOTATIONS);
    /**
     * @param o 被转换对象
     * @return 字符串
     * @throws JsonProcessingException
     */
    public static <T> String toJson(T o) {
        try {

            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {

            throw new RuntimeException("实体转换成json出错",e);
        }
    }
    /**
     JSON串转换为Java泛型对象
     * @param s JSON字符串
     * @param tr TypeReference,例如: new TypeReference< List<User> >(){}
     * @return List对象列表
     */
    public static <T> T toObject(String s, TypeReference<T> tr) {
        try {
            return mapper.readValue(s, tr);
        } catch (IOException e) {
            throw new RuntimeException("json转换成实体出错",e);
        }
    }

    /**
     非泛型转换
     */
    public static <T> T toObject(String s, Class<T> tClass) {
        try {
            return mapper.readValue(s,tClass);
        } catch (IOException e) {
            throw new RuntimeException("json转换成实体出错",e);
        }
    }
}
